package com.example.demo.service.impl;

import com.example.demo.DTO.DeviceDTO;
import com.example.demo.Exception.DeviceException;
import com.example.demo.dataobject.Device;
import com.example.demo.dataobject.DeviceS;
import com.example.demo.repository.DeviceRespository;
import com.example.demo.repository.DeviceSRespository;
import com.example.demo.service.DeviceService;
import com.example.demo.enums.ExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.NoSuchElementException;

@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private DeviceRespository device;

    @Autowired
    private DeviceSRespository device_s;

    @Override
    public Device findOne(Integer id) {
        try {
            return device.findById(id).get();
        }
        catch (NoSuchElementException e ){
            return null;
        }
    }

    @Override
    public List<Device> findAll() {
        return device.findAll();
    }

    @Override
    public DeviceDTO findwith(Integer id){
        Device result = device.findById(id).get();
        if(result == null){
            throw new DeviceException(ExceptionEnum.DEVICE_NOT_EXIST);
        }
        List<DeviceS> results = device_s.findByDeviceId(result.getId());

        return new DeviceDTO(result,results);
    }
}
